package com.rookie.im.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Handles a server-side channel.
 */
public class HeartBeatServerHandler extends SimpleChannelInboundHandler<String> { // (1)

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("========客户端" + ctx.channel().remoteAddress() + "连接");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("========客户端" + ctx.channel().remoteAddress() + "断开");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("========服务端" + channelHandlerContext.channel().remoteAddress() + "接收消息： " + s);
        if ("Netty Heartbeat".equals(s)) {
            channelHandlerContext.channel().writeAndFlush("ok");
        }
    }
    private int timeoutRetry = 0;
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (!(evt instanceof IdleStateEvent)) {
            return;
        }
        IdleStateEvent event = (IdleStateEvent) evt;
        String eventType = "";
        switch (event.state()) {
            case READER_IDLE:
                timeoutRetry++;
                eventType = "读空闲";
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                break;
            case ALL_IDLE:
                eventType = "全空闲";
                break;
        }
        System.out.println("超时事件: " + eventType);
        if (timeoutRetry > 3) {
            System.out.println("读空闲超时3次,关闭连接,回收资源");
            ctx.channel().writeAndFlush("idle close");
            ctx.channel().close();
        }
    }
}